var entityCollection = require('../../../Base/server/controllers/EntityCollection');

//查找条码流水
exports.findByBarcodeMasterAndWork = function(barcodMasterId, workId, completeFun){
    var entity = entityCollection.getEntity("BizRecord");
    entity.findOne({BarcodeMaster: barcodMasterId, Work: workId}, [{path: 'Users'}, {path: 'QCUser'}], function(err, record){
        if(err){
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '语法错误，请检查查询参数！';
            completeFun(newErr);
        }
        else{
            completeFun(null, record);
        }
    });
};

//创建条码流水
exports.insert = function(bizRecordData, completeFun){
    var bizRecordEntity = entityCollection.getEntity("BizRecord");
    bizRecordEntity.insert(bizRecordData, function(err, newBizRecord){
        completeFun(err, newBizRecord);
    });
};

//删除条码流水
exports.deleteById = function(bizRecordId, completeFun){
    var bizRecordEntity = entityCollection.getEntity("BizRecord");
    bizRecordEntity.deleteById(bizRecordId, function(err, result){
        completeFun(err, result);
    });
};

// 查找单品所有流水，并按部门分组
exports.findByBarcodeMaster = function (barcodeMasterId, completeFun) {
    var entity = entityCollection.getEntity("BizRecord");
    entity.find(
        {BarcodeMaster: barcodeMasterId}, 
        {CollectDateTime: 1}, [{
            path: 'Users',
            select: 'Code Name'
        }, {
            path: 'WorkLocation',
            select: 'Code Name Department',
            populate: {
                path: 'Department',
                select: 'Code Name',
                model: 'Department'
            }
        }], function(err, records) {
        if(err){
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '语法错误，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};

// 仅供压力测试使用：更新一条条码流水记录
exports.updateOneST = function (barcodMasterId, completeFun) {
    var entity = entityCollection.getEntity("BizRecord");
    entity.findOne({BarcodeMaster: barcodMasterId}, null, function(err, record) {
        if (err || !record) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '语法错误，请检查查询参数！';
            completeFun(newErr);
            return;
        }
        record.BusinessStatus = 1;
        entity.update(record, function(err, modifyRecord) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询错误';
                newErr.message = '语法错误，请检查查询参数！';
                completeFun(newErr);
                return;
            }
            completeFun(null, modifyRecord);
        });
    });
};